import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/MainPage/MainXTNewsPage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class UserManagePage extends StatefulWidget {
  UserManagePage({Key key}) : super(key: key);

  @override
  _NewsManagePageState createState() => _NewsManagePageState();
}

class _NewsManagePageState extends State<UserManagePage> {
  List<CellModel> cellArr = [];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  int page = 1;

  void _onRefresh() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    page = 1;
    cellArr?.clear();
    getCellNews();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    // items.add((items.length + 1).toString());
    page = page + 1;
    getCellNews();
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
  }

  void getCellNews() {
    DioUtils.postHttp(
      context,
      "Usercenter/app_news",
      parameters: {
        "token": getData("token"),
        "page": page.toString(),
      },
      onSuccess: (t) {
        print(t);
        ListModel model = ListModel.fromJson(t);
        if (model.code == 1) {
          if (mounted) {
            setState(() {
              List<CellModel> arr = model.data;
              for (var i = 0; i < arr.length; i++) {
                cellArr.add(arr[i]);
              }
            });
          }
        }
      },
      onError: (error) {
        print(error);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: getAppBar(context, "消息管理"),
      appBar: AppBar(
        title: Text("消息管理"),
        elevation: 0,
        centerTitle: true,
        leading: IconButton(
          icon: Image.asset(
            "images/MainBackImage.png",
            height: 20,
            width: 20,
            color: Colors.black,
          ),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          IconButton(
            icon: Image.asset(
              "images/MainRemoveImage.png",
              height: 20,
              width: 20,
              color: Colors.black,
            ),
            onPressed: () {
              showAlertDialog(context);
            },
          )
        ],
      ),
      body: SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = Text("上拉加载");
            } else if (mode == LoadStatus.loading) {
              body = CupertinoActivityIndicator();
            } else if (mode == LoadStatus.failed) {
              body = Text("加载失败！点击重试！");
            } else if (mode == LoadStatus.canLoading) {
              body = Text("松手,加载更多!");
            } else {
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: cellArr.length == 0
            ? Container()
            : ListView.builder(
                itemCount: cellArr.length,
                itemBuilder: _listItemBuilder,
              ),
      ),
    );
  }

  showAlertDialog(BuildContext context) {
    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text("确定要删除去全部消息吗?"),
          // content: Text("确定要退出吗?"),
          // 设置成 圆角
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          actions: [
            FlatButton(
              child: Text(
                "取消",
                style: TextStyle(
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            ),
            FlatButton(
              child: Text(
                "确认",
                style: TextStyle(
                  color: Colors.orange,
                  fontSize: setFontSize(30),
                ),
              ),
              onPressed: () {
                DioUtils.postHttp(
                  context,
                  "Usercenter/news_delete",
                  parameters: {"token": getData("token")},
                  onSuccess: (t) {
                    print(t);
                    Navigator.pop(context);
                    _onRefresh();
                  },
                  onError: (error) {
                    Navigator.pop(context);
                  },
                );
              },
            ),
          ],
        );
      },
    );
  }

  Widget _listItemBuilder(BuildContext context, int index) {
    return InkWell(
      child: Container(
        padding: EdgeInsets.fromLTRB(
          setWidth(30),
          setWidth(20),
          setWidth(30),
          setWidth(0),
        ),
        child: Row(
          children: [
            ClipOval(
              child: Image.asset(
                "images/XiTongNewsImage.png",
                height: setHeight(100),
                width: setHeight(100),
              ),
            ),
            SizedBox(width: 10),
            Expanded(
                child: Column(
              children: <Widget>[
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text(
                      "系统消息",
                      style: TextStyle(
                        color: Color(0xFF222222),
                        fontSize: setFontSize(32),
                      ),
                    ),
                    Text(
                      cellArr[index].createtimeText,
                      style: TextStyle(
                          color: Colors.grey[400], fontSize: setFontSize(30)),
                    ),
                  ],
                ),
                SizedBox(height: 4),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Expanded(
                      child: Text(
                        cellArr[index].content,
                        style: TextStyle(color: Color(0xFF666666)),
                      ),
                    ),
                    SizedBox(width: 4),
                    cellArr[index].num > 0
                        ? Container(
                            height: 20.0,
                            alignment: Alignment.center,
                            padding: EdgeInsets.only(left: 10.0, right: 10.0),
                            decoration: BoxDecoration(
                              color: Colors.red,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10.0)),
                            ),
                            child: Text(
                              cellArr[index].num.toString(),
                              style: TextStyle(color: Colors.white),
                            ),
                          )
                        : Container(),
                  ],
                ),
                SizedBox(height: 8),
                Container(
                  color: Colors.grey[400],
                  width: 900,
                  height: 1,
                ),
              ],
            ))
          ],
        ),
      ),
      onTap: () {
        print("object" + index.toString());
        Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) =>
                  MainXTNewsPage(cellArr[index].orderId.toString())),
        ).then((value) {
          _onRefresh();
        });
      },
    );
  }
}

class ListModel {
  int code;
  String msg;
  String time;
  List<CellModel> data;

  ListModel({this.code, this.msg, this.time, this.data});

  ListModel.fromJson(Map<String, dynamic> json) {
    code = json['code'];
    msg = json['msg'];
    time = json['time'];
    if (json['data'] != null) {
      data = new List<CellModel>();
      json['data'].forEach((v) {
        data.add(new CellModel.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['code'] = this.code;
    data['msg'] = this.msg;
    data['time'] = this.time;
    if (this.data != null) {
      data['data'] = this.data.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class CellModel {
  int id;
  int orderId;
  int userId;
  String content;
  int num;
  int createtime;
  String createtimeText;

  CellModel(
      {this.id,
      this.orderId,
      this.userId,
      this.content,
      this.num,
      this.createtime,
      this.createtimeText});

  CellModel.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    orderId = json['order_id'];
    userId = json['user_id'];
    content = json['content'];
    num = json['num'];
    createtime = json['createtime'];
    createtimeText = json['createtime_text'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['order_id'] = this.orderId;
    data['user_id'] = this.userId;
    data['content'] = this.content;
    data['num'] = this.num;
    data['createtime'] = this.createtime;
    data['createtime_text'] = this.createtimeText;
    return data;
  }
}
